package com.plpm.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.beans.factory.annotation.Value;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Arrays;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.plpm.config.SelectOptionsConfig;
import com.plpm.mapper.FileRecordMapper;
import com.plpm.model.ImportTask;
import com.plpm.service.FileRecordService;
import com.plpm.service.ImportTaskService;
import com.plpm.service.IoTDBService;
import com.plpm.vo.FileRecordVO;

import lombok.extern.slf4j.Slf4j;

/**
 * 文件记录控制器
 *
 * @author PLPM Team
 * @version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/file-record")
public class FileRecordController {

    @Autowired
    private FileRecordMapper fileRecordMapper;

    @Autowired
    private FileRecordService fileRecordService;

    @Autowired
    private IoTDBService iotdbService;

    @Autowired
    private SelectOptionsConfig selectOptionsConfig;

    @Autowired
    private ImportTaskService importTaskService;
    
    @Value("${file.upload.path}")
    private String uploadPath;

    /**
     * 创建配置好的ObjectMapper实例，支持LocalDateTime等Java 8时间类型
     */
    private ObjectMapper createObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 注册JavaTimeModule以支持LocalDateTime等Java 8时间类型的序列化/反序列化
        objectMapper.registerModule(new JavaTimeModule());
        // 禁用时间戳序列化，使用字符串格式
        objectMapper.disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return objectMapper;
    }


    /**
     * 插入单个文件记录
     */
    @PostMapping("/insert")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> insertFileRecord(@RequestBody FileRecordVO fileRecordVO) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 调用Service层方法
            FileRecordService.InsertResult insertResult = fileRecordService.insertFileRecord(fileRecordVO);

            result.put("success", insertResult.isSuccess());
            result.put("message", insertResult.getMessage());
            result.put("timestamp", System.currentTimeMillis());

            if (insertResult.isSuccess()) {
                result.put("insertCount", insertResult.getInsertCount());
                result.put("fileName", insertResult.getFileName());
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }

        } catch (Exception e) {
            log.error("插入文件记录时发生异常", e);
            result.put("success", false);
            result.put("message", "插入文件记录时发生异常: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 批量插入文件记录
     */
    @PostMapping("/batch-insert")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> batchInsertFileRecords(@RequestBody List<FileRecordVO> fileRecordVOs) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 调用Service层方法
            FileRecordService.BatchInsertResult batchInsertResult = fileRecordService.batchInsertFileRecords(fileRecordVOs);

            result.put("success", batchInsertResult.isSuccess());
            result.put("message", batchInsertResult.getMessage());
            result.put("timestamp", System.currentTimeMillis());

            if (batchInsertResult.isSuccess()) {
                result.put("insertCount", batchInsertResult.getInsertCount());
                result.put("totalCount", batchInsertResult.getTotalCount());
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }

        } catch (Exception e) {
            log.error("批量插入文件记录时发生异常", e);
            result.put("success", false);
            result.put("message", "批量插入文件记录时发生异常: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 批量更新文件记录
     */
    @PostMapping("/batch-update")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> batchUpdateFileRecords(@RequestBody List<FileRecordVO> fileRecordVOs) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 调用Service层方法
            FileRecordService.BatchUpdateResult batchUpdateResult = fileRecordService.batchUpdateFileRecords(fileRecordVOs);

            result.put("success", batchUpdateResult.isSuccess());
            result.put("message", batchUpdateResult.getMessage());
            result.put("timestamp", System.currentTimeMillis());

            if (batchUpdateResult.isSuccess()) {
                result.put("updateCount", batchUpdateResult.getUpdateCount());
                result.put("totalCount", batchUpdateResult.getTotalCount());
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }

        } catch (Exception e) {
            log.error("批量更新文件记录时发生异常", e);
            result.put("success", false);
            result.put("message", "批量更新文件记录时发生异常: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 单条更新文件记录
     */
    @PutMapping("/update")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> updateFileRecord(@RequestBody FileRecordVO fileRecordVO) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 调用Service层方法
            FileRecordService.UpdateResult updateResult = fileRecordService.updateFileRecord(fileRecordVO);

            result.put("success", updateResult.isSuccess());
            result.put("message", updateResult.getMessage());
            result.put("timestamp", System.currentTimeMillis());

            if (updateResult.isSuccess()) {
                result.put("updateCount", updateResult.getUpdateCount());
                result.put("recordId", updateResult.getRecordId());
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.badRequest().body(result);
            }

        } catch (Exception e) {
            log.error("更新文件记录时发生异常", e);
            result.put("success", false);
            result.put("message", "更新文件记录时发生异常: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 获取选择器选项配置
     */
    @GetMapping("/select-options")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getSelectOptions() {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> options = new HashMap<>();
            options.put("productPhase", selectOptionsConfig.getProductPhase());
            options.put("dataTypeFirst", selectOptionsConfig.getDataTypeFirst());
            options.put("dataTypeSecond", selectOptionsConfig.getDataTypeSecond());
            options.put("dataSource", selectOptionsConfig.getDataSource());
            options.put("channelNo", selectOptionsConfig.getChannelNo());
            options.put("projectNo", selectOptionsConfig.getProjectNo());
            
            result.put("success", true);
            result.put("data", options);
            result.put("message", "获取选择器选项成功");
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取选择器选项失败", e);
            result.put("success", false);
            result.put("message", "获取选择器选项失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 分页查询文件记录
     */
    @GetMapping("/query-paginated")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> queryFileRecordsPaginated(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Integer uploadStatus,
            @RequestParam(required = false) Integer importStatus) {
        Map<String, Object> result = new HashMap<>();

        try {
            log.info("开始分页查询文件记录，页码: {}, 页大小: {}, 上传状态: {}, 导入状态: {}", page, size, uploadStatus, importStatus);

            // 参数验证
            if (page < 1) {
                page = 1;
            }
            if (size < 1 || size > 100) {
                size = 10;
            }

            // 计算偏移量
            int offset = (page - 1) * size;

            List<FileRecordVO> records;
            int totalCount;

            // 特殊处理：当uploadStatus为null且importStatus为2时，表示查询异常文件
            // 异常文件包括：上传失败(uploadStatus=2) 或 上传成功但导入失败(uploadStatus=1且importStatus=2)
            if (Objects.isNull(uploadStatus) && Objects.nonNull(importStatus) && importStatus == 2) {
                log.info("查询异常文件：上传失败或上传成功但导入失败");
                records = fileRecordMapper.findErrorFilesWithPagination(importStatus, offset, size);
                totalCount = fileRecordMapper.countErrorFiles(importStatus);
            } else if (Objects.isNull(uploadStatus)) {
                log.error("分页查询文件记录时，uploadStatus为空且不是异常文件查询");
                result.put("success", false);
                result.put("message", "分页查询文件记录时发生异常:uploadStatus为空");
                result.put("timestamp", System.currentTimeMillis());
                return ResponseEntity.status(500).body(result);
            } else {
                // 查询分页数据
                log.info("调用Mapper查询，参数: uploadStatus={}, importStatus={}, offset={}, size={}", uploadStatus, importStatus, offset, size);
                records = fileRecordMapper.findByUploadAndImportStatusWithPagination(uploadStatus, importStatus, offset, size);
                log.info("查询结果数量: {}", records.size());
                
                // 添加详细日志：打印每条记录的详细信息
                if (records != null && !records.isEmpty()) {
                    log.info("查询到的文件记录详情（共{}条）:", records.size());
                    java.util.Map<String, Integer> fileNameCount = new java.util.HashMap<>();
                    for (FileRecordVO record : records) {
                        String fileName = record.getFileName();
                        fileNameCount.put(fileName, fileNameCount.getOrDefault(fileName, 0) + 1);
                        
                        log.info("  - 文件ID: {}, 文件名: {}, 项目编号: {}, 发动机编号: {}, 发动机位置: {}, 台架编号: {}, 上传时间: {}, 上传状态: {}, 导入状态: {}",
                                record.getId(),
                                record.getFileName(),
                                record.getProjectNo(),
                                record.getEngineNo(),
                                record.getEnginePlace(),
                                record.getDeviceNo(),
                                record.getUploadTime(),
                                record.getUploadStatus(),
                                record.getImportStatus());
                    }
                    
                    // 检查是否有重复的文件名
                    fileNameCount.forEach((fileName, count) -> {
                        if (count > 1) {
                            log.warn("⚠️ 检测到重复的文件名: '{}' 出现了 {} 次！", fileName, count);
                        }
                    });
                }
                
                // 查询总记录数
                int countResult = fileRecordMapper.countByUploadAndImportStatus(uploadStatus, importStatus);
                log.info("COUNT查询返回的总记录数: {}", countResult);
                log.info("实际返回的记录数量: {}", records.size());
                
                // 如果COUNT查询结果与实际返回数量不一致，记录警告并使用实际数量
                // 这种情况可能是因为import_task表中缺少某些文件的记录，导致COUNT查询不准确
                if (countResult != records.size()) {
                    log.warn("⚠️ COUNT查询返回{}条，但实际返回{}条记录。这可能是由于import_task表中缺少部分文件的记录。使用实际返回数量作为totalCount以确保分页正确。", countResult, records.size());
                    // 对于分页，使用实际返回的数量更准确
                    // 如果返回的记录数等于pageSize，说明可能还有更多记录，需要估算totalCount
                    if (records.size() < size) {
                        // 返回数量小于pageSize，说明这是最后一页，totalCount就是实际返回的数量
                        totalCount = records.size();
                    } else {
                        // 返回数量等于pageSize，可能还有更多记录
                        // 使用COUNT查询结果和实际返回数量的较大值，确保分页信息正确
                        totalCount = Math.max(countResult, offset + records.size());
                        log.info("估算totalCount: {} (offset: {}, 返回数量: {})", totalCount, offset, records.size());
                    }
                } else {
                    totalCount = countResult;
                }
            }

            // 计算总页数
            int totalPages = (int) Math.ceil((double) totalCount / size);

            result.put("success", true);
            result.put("message", "分页查询文件记录成功");
            result.put("data", records);
            Map<String, Object> paginationInfo = new HashMap<>();
            paginationInfo.put("currentPage", page);
            paginationInfo.put("pageSize", size);
            paginationInfo.put("totalCount", totalCount);
            paginationInfo.put("totalPages", totalPages);
            paginationInfo.put("hasNext", page < totalPages);
            paginationInfo.put("hasPrevious", page > 1);
            result.put("pagination", paginationInfo);
            result.put("timestamp", System.currentTimeMillis());

            log.info("分页查询文件记录成功，共{}条记录，当前页: {}/{}，返回{}条数据", totalCount, page, totalPages, records.size());
            
            // 检查返回的数据中是否有重复的文件名或ID
            if (records != null && records.size() > 1) {
                java.util.Set<String> fileNames = new java.util.HashSet<>();
                java.util.Set<Long> recordIds = new java.util.HashSet<>();
                for (FileRecordVO record : records) {
                    if (record.getFileName() != null && !fileNames.add(record.getFileName())) {
                        log.warn("检测到重复的文件名: {}", record.getFileName());
                    }
                    if (record.getId() != null && !recordIds.add(record.getId())) {
                        log.warn("检测到重复的文件ID: {}, 文件名: {}", record.getId(), record.getFileName());
                    }
                }
                
                // 打印所有返回的记录ID和文件名，方便调试
                log.info("返回的所有记录ID和文件名列表:");
                for (FileRecordVO record : records) {
                    log.info("  - ID: {}, 文件名: {}", record.getId(), record.getFileName());
                }
            }
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("分页查询文件记录时发生异常", e);
            result.put("success", false);
            result.put("message", "分页查询文件记录时发生异常: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 根据文件名查询文件记录
     */
    @GetMapping("/query-by-filename")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> queryByFileName(String fileName) {
        Map<String, Object> result = new HashMap<>();

        try {
            log.info("开始根据文件名查询文件记录: {}", fileName);

            // 根据同文件名且upload_status=1的记录
            FileRecordVO record = fileRecordMapper.findSuccessRecordByFileName(fileName);

            result.put("success", true);
            result.put("message", "查询文件记录成功");
            result.put("record", record);
            result.put("timestamp", System.currentTimeMillis());

            log.info("根据文件名查询文件记录成功: {}", fileName);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("根据文件名查询文件记录时发生异常", e);
            result.put("success", false);
            result.put("message", "根据文件名查询文件记录时发生异常: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 批量根据文件名查询文件记录
     */
    @PostMapping("/batch-query-by-filenames")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> batchQueryByFileNames(@RequestBody List<String> fileNames) {
        Map<String, Object> result = new HashMap<>();

        try {
            log.info("开始批量查询文件记录，文件数量: {}", fileNames != null ? fileNames.size() : 0);

            if (fileNames == null || fileNames.isEmpty()) {
                result.put("success", true);
                result.put("message", "查询文件记录成功");
                result.put("records", new java.util.ArrayList<>());
                result.put("timestamp", System.currentTimeMillis());
                return ResponseEntity.ok(result);
            }

            // 批量查询 upload_status=1 的记录
            List<FileRecordVO> records = fileRecordMapper.findSuccessRecordsByFileNames(fileNames);

            // 构建文件名到记录的映射，方便前端查找
            Map<String, FileRecordVO> recordMap = new HashMap<>();
            if (records != null) {
                for (FileRecordVO record : records) {
                    if (record.getFileName() != null) {
                        recordMap.put(record.getFileName(), record);
                    }
                }
            }

            result.put("success", true);
            result.put("message", "批量查询文件记录成功");
            result.put("records", records);
            result.put("recordMap", recordMap); // 提供映射方便前端使用
            result.put("timestamp", System.currentTimeMillis());

            log.info("批量查询文件记录成功，查询{}个文件名，返回{}条记录", 
                    fileNames.size(), records != null ? records.size() : 0);
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("批量查询文件记录时发生异常", e);
            result.put("success", false);
            result.put("message", "批量查询文件记录时发生异常: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 根据项目编号查询文件记录列表
     */
    @GetMapping("/query-by-project")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> queryByProjectNo(String projectNo) {
        Map<String, Object> result = new HashMap<>();

        try {
            log.info("开始根据项目编号查询文件记录: {}", projectNo);

            // 根据项目编号查询记录列表
            List<FileRecordVO> records = fileRecordMapper.findByProjectNo(projectNo);

            result.put("success", true);
            result.put("message", "根据项目编号查询文件记录成功");
            result.put("projectNo", projectNo);
            result.put("recordCount", records.size());
            result.put("records", records);
            result.put("timestamp", System.currentTimeMillis());

            log.info("根据项目编号查询文件记录成功: {}, 共{}条记录", projectNo, records.size());
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("根据项目编号查询文件记录时发生异常", e);
            result.put("success", false);
            result.put("message", "根据项目编号查询文件记录时发生异常: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 检查文件是否存在于上传目录
     */
    @GetMapping("/check-file-exists")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> checkFileExists(@RequestParam String fileName) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (fileName == null || fileName.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "文件名不能为空");
                result.put("exists", false);
                return ResponseEntity.badRequest().body(result);
            }
            
            // 检查文件是否存在于上传目录
            java.nio.file.Path filePath = java.nio.file.Paths.get(uploadPath, fileName);
            boolean exists = java.nio.file.Files.exists(filePath);
            
            result.put("success", true);
            result.put("exists", exists);
            result.put("message", exists ? "文件存在" : "文件不存在");
            result.put("filePath", filePath.toString());
            
            log.info("检查文件存在性: {}, 结果: {}", fileName, exists);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("检查文件存在性失败: {}", fileName, e);
            result.put("success", false);
            result.put("message", "检查文件存在性失败: " + e.getMessage());
            result.put("exists", false);
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 批量检查文件是否存在于上传目录
     */
    @PostMapping("/batch-check-file-exists")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> batchCheckFileExists(@RequestBody List<String> fileNames) {
        Map<String, Object> result = new HashMap<>();
        try {
            log.info("开始批量检查文件存在性，文件数量: {}", fileNames != null ? fileNames.size() : 0);

            if (fileNames == null || fileNames.isEmpty()) {
                result.put("success", true);
                result.put("message", "批量检查文件存在性成功");
                result.put("fileExistsMap", new java.util.HashMap<>());
                result.put("timestamp", System.currentTimeMillis());
                return ResponseEntity.ok(result);
            }

            // 批量检查文件是否存在
            Map<String, Boolean> fileExistsMap = new HashMap<>();
            for (String fileName : fileNames) {
                if (fileName != null && !fileName.trim().isEmpty()) {
                    try {
                        java.nio.file.Path filePath = java.nio.file.Paths.get(uploadPath, fileName);
                        boolean exists = java.nio.file.Files.exists(filePath);
                        fileExistsMap.put(fileName, exists);
                    } catch (Exception e) {
                        log.warn("检查文件存在性失败: {}", fileName, e);
                        fileExistsMap.put(fileName, false); // 检查失败时默认为不存在
                    }
                } else {
                    fileExistsMap.put(fileName, false);
                }
            }

            result.put("success", true);
            result.put("message", "批量检查文件存在性成功");
            result.put("fileExistsMap", fileExistsMap);
            result.put("timestamp", System.currentTimeMillis());

            log.info("批量检查文件存在性成功，检查{}个文件", fileNames.size());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("批量检查文件存在性失败", e);
            result.put("success", false);
            result.put("message", "批量检查文件存在性失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(500).body(result);
        }
    }


    /**
     * 批量导入文件到IoTDB
     */
    @PostMapping("/batch-import-files")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> batchImportFiles(@RequestBody List<FileRecordVO> fileRecordVOs) {
        try {
            log.info("开始批量导入文件到IoTDB，文件数量: {}", fileRecordVOs != null ? fileRecordVOs.size() : 0);
            
            // 调用内部批量导入逻辑，统一使用文件系统读取
            return batchImportFilesInternal(fileRecordVOs);
            
        } catch (Exception e) {
            log.error("批量导入文件失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "批量导入失败: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 从文件系统读取文件内容
     */
    private void loadFileContentFromFileSystem(FileRecordVO fileRecordVO) {
        try {
            String fileName = fileRecordVO.getFileName();
            if (fileName == null || fileName.trim().isEmpty()) {
                log.warn("文件名为空，无法读取文件内容");
                fileRecordVO.setBinaryFile(new byte[0]);
                return;
            }
            
            // 使用配置文件中的上传路径
            java.nio.file.Path filePath = java.nio.file.Paths.get(uploadPath, fileName);
            
            if (java.nio.file.Files.exists(filePath)) {
                byte[] fileContent = java.nio.file.Files.readAllBytes(filePath);
                fileRecordVO.setBinaryFile(fileContent);
                log.info("文件内容已从文件系统加载: {}, 大小: {} bytes", fileName, fileContent.length);
            } else {
                log.warn("文件不存在于文件系统: {}", filePath);
                fileRecordVO.setBinaryFile(new byte[0]);
            }
        } catch (Exception e) {
            log.error("从文件系统读取文件内容失败: {}", fileRecordVO.getFileName(), e);
            fileRecordVO.setBinaryFile(new byte[0]);
        }
    }

    /**
     * 内部批量导入逻辑（统一处理单个和批量导入）
     */
    private ResponseEntity<Map<String, Object>> batchImportFilesInternal(List<FileRecordVO> fileRecordVOs) {
        Map<String, Object> result = new HashMap<>();

        try {
            log.info("开始批量导入文件到IoTDB，文件数量: {}", 
                    fileRecordVOs != null ? fileRecordVOs.size() : 0);

            // 参数验证
            if (fileRecordVOs == null || fileRecordVOs.isEmpty()) {
                result.put("success", false);
                result.put("message", "文件配置数据不能为空");
                result.put("timestamp", System.currentTimeMillis());
                return ResponseEntity.badRequest().body(result);
            }

            // 必填字段校验
            List<String> allMissingFields = new ArrayList<>();
            List<String> invalidFileNames = new ArrayList<>();
            for (FileRecordVO fileRecordVO : fileRecordVOs) {
                Map<String, Object> validationResult = validateRequiredFields(fileRecordVO);
                if (!(Boolean) validationResult.get("success")) {
                    String fileName = fileRecordVO.getFileName() != null ? fileRecordVO.getFileName() : "未知文件";
                    invalidFileNames.add(fileName);
                    String message = (String) validationResult.get("message");
                    // 提取缺失字段列表
                    if (message.contains("：")) {
                        String missingFields = message.substring(message.indexOf("：") + 1);
                        if (!allMissingFields.contains(missingFields)) {
                            allMissingFields.add(missingFields);
                        }
                    }
                }
            }
            
            if (!invalidFileNames.isEmpty()) {
                String errorMessage;
                if (invalidFileNames.size() == 1) {
                    errorMessage = String.format("请先填写以下必填字段后再导入：%s", 
                        String.join("、", allMissingFields));
                } else {
                    errorMessage = String.format("以下文件缺少必填字段，请先填写后再导入：%s\n缺少字段：%s", 
                        String.join("、", invalidFileNames.subList(0, Math.min(5, invalidFileNames.size()))) + 
                        (invalidFileNames.size() > 5 ? "..." : ""),
                        String.join("、", allMissingFields));
                }
                result.put("success", false);
                result.put("message", errorMessage);
                result.put("timestamp", System.currentTimeMillis());
                return ResponseEntity.badRequest().body(result);
            }

            // 统一从文件系统读取文件内容，把文件转为二进制存到binary_file字段
            log.info("从文件系统读取文件内容");
            for (FileRecordVO fileRecordVO : fileRecordVOs) {
                loadFileContentFromFileSystem(fileRecordVO);
            }

            log.info("批量导入文件数量: {}", fileRecordVOs.size());

            /*  导入步骤
            1. fileRecord信息存到IoTDB数据库，生成时间序列（数据来自前端传递的fileRecordVO，已通过"修改标签"更新过）
            2. 根据上一步的导入结果，将fileRecordVO的字段，插入import_task表，新增task记录，并附带导入结果import_status(导入状态（0-未导入；1-导入成功；2-导入失败）)
            */
            // 步骤1：调用IoTDB服务进行批量导入
            log.info("步骤1：开始导入到IoTDB数据库");
            Map<String, Object> importResult = iotdbService.batchImportFilesToIoTDB(fileRecordVOs);
            
            // 步骤2：根据导入结果创建import_task记录
            log.info("步骤2：根据导入结果创建import_task记录");
            Map<String, Object> taskResult = createImportTasksWithResults(fileRecordVOs, importResult);
            if (!(Boolean) taskResult.get("success")) {
                log.warn("创建import_task记录失败: {}", taskResult.get("message"));
                // 注意：这里不直接返回错误，因为IoTDB导入可能已经成功
            }

            // 添加时间戳
            importResult.put("timestamp", System.currentTimeMillis());

            return ResponseEntity.ok(importResult);

        } catch (Exception e) {
            log.error("批量导入文件到IoTDB时发生异常", e);
            result.put("success", false);
            result.put("message", "批量导入文件到IoTDB时发生异常: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 步骤1：批量更新fileRecord表
     * 根据fileRecord_id和file_name更新记录
     */
    private Map<String, Object> updateFileRecordsInBatch(List<FileRecordVO> fileRecordVOs) {
        return executeBatchOperation(
            "批量更新fileRecord表",
            () -> {
                log.info("开始批量更新fileRecord表，记录数量: {}", fileRecordVOs.size());
                FileRecordService.BatchUpdateResult updateResult = fileRecordService.batchUpdateFileRecords(fileRecordVOs);
                
                if (updateResult.isSuccess()) {
                    log.info("批量更新fileRecord表成功，更新数量: {}", updateResult.getUpdateCount());
                    Map<String, Object> additionalData = new HashMap<>();
                    additionalData.put("updateCount", updateResult.getUpdateCount());
                    return createSuccessResult(
                        String.format("成功更新%d条fileRecord记录", updateResult.getUpdateCount()),
                        additionalData
                    );
                } else {
                    log.error("批量更新fileRecord表失败: {}", updateResult.getMessage());
                    return createErrorResult("批量更新fileRecord表失败: " + updateResult.getMessage());
                }
            }
        );
    }


    /**
     * 步骤2.2：根据导入结果创建import_task记录
     * 根据IoTDB导入结果设置import_status状态
     */
    private Map<String, Object> createImportTasksWithResults(List<FileRecordVO> fileRecordVOs, Map<String, Object> importResult) {
        return executeBatchOperation(
            "根据导入结果创建import_task记录",
            () -> {
                log.info("开始根据导入结果创建import_task记录，记录数量: {}", fileRecordVOs.size());
                
                // 获取导入结果详情
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> importResults = (List<Map<String, Object>>) importResult.get("importResults");
                
                if (importResults == null || importResults.isEmpty()) {
                    log.warn("导入结果为空，无法创建import_task记录");
                    return createErrorResult("导入结果为空，无法创建import_task记录");
                }
                
                // 批量查询已存在的ImportTask，避免在循环中重复查询数据库
                List<String> fileNames = fileRecordVOs.stream()
                    .map(FileRecordVO::getFileName)
                    .collect(java.util.stream.Collectors.toList());
                List<ImportTask> existingTasks = importTaskService.findByFileNames(fileNames);
                Map<String, ImportTask> existingTaskMap = existingTasks.stream()
                    .collect(java.util.stream.Collectors.toMap(ImportTask::getFileName, task -> task));
                
                // 将FileRecordVO转换为ImportTask，并根据导入结果设置状态
                List<ImportTask> importTasks = new ArrayList<>();
                
                for (int i = 0; i < fileRecordVOs.size() && i < importResults.size(); i++) {
                    FileRecordVO fileRecordVO = fileRecordVOs.get(i);
                    Map<String, Object> result = importResults.get(i);

                    ImportTask importTask = convertFileRecordVOToImportTask(fileRecordVO);
                    //检测importTask中filename，在importTask表中是否已存在，
                    //若不存在，retrytime为1，若存在retrytime则+1
                    ImportTask existingTask = existingTaskMap.get(fileRecordVO.getFileName());
                    if (existingTask != null) {
                        // 如果已存在，retrytime +1
                        importTask.setRetryTime(existingTask.getRetryTime() + 1);
                    } else {
                        // 如果不存在，retrytime为1
                        importTask.setRetryTime(1);
                    }

                    // 根据导入结果设置import_status
                    boolean success = (Boolean) result.getOrDefault("success", false);
                    importTask.setImportStatus(success ? 1 : 2); // 1-导入成功；2-导入失败
                    // 如果导入失败，记录错误信息，并将错误信息放入remark字段
                    if (!success) {
                        String errorMessage = (String) result.getOrDefault("message", "导入失败");
                        log.warn("文件 {} 导入失败: {}", fileRecordVO.getFileName(), errorMessage);
                        // 将错误信息放入remark字段
                        importTask.setRemark(errorMessage);
                    }
                    
                    importTasks.add(importTask);
                }
                
                // 调用Service层进行批量插入
                int insertCount = importTaskService.batchCreateImportTasks(importTasks);
                
                if (insertCount > 0) {
                    log.info("根据导入结果创建import_task记录成功，插入数量: {}", insertCount);
                    Map<String, Object> additionalData = new HashMap<>();
                    additionalData.put("insertCount", insertCount);
                    return createSuccessResult(
                        String.format("成功创建%d条import_task记录", insertCount),
                        additionalData
                    );
                } else {
                    log.error("根据导入结果创建import_task记录失败，没有记录被插入");
                    return createErrorResult("根据导入结果创建import_task记录失败，没有记录被插入");
                }
            }
        );
    }

    /**
     * 执行批量操作的通用方法（消除重复的错误处理代码）
     */
    private Map<String, Object> executeBatchOperation(String operationName, Supplier<Map<String, Object>> operation) {
        try {
            return operation.get();
        } catch (Exception e) {
            log.error("{}时发生异常", operationName, e);
            return createErrorResult(operationName + "时发生异常: " + e.getMessage());
        }
    }

    /**
     * 创建成功结果
     */
    private Map<String, Object> createSuccessResult(String message, Map<String, Object> additionalData) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", message);
        if (additionalData != null) {
            result.putAll(additionalData);
        }
        return result;
    }

    /**
     * 创建错误结果
     */
    private Map<String, Object> createErrorResult(String message) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", message);
        return result;
    }

    /**
     * 必填项校验
     */
    private Map<String, Object> validateRequiredFields(FileRecordVO fileRecordVO) {
        Map<String, Object> result = new HashMap<>();
        List<String> missingFields = new ArrayList<>();

        // 定义必填字段
        if (fileRecordVO.getProjectNo() == null || fileRecordVO.getProjectNo().trim().isEmpty()) {
            missingFields.add("项目编号");
        }
        if (fileRecordVO.getDeviceNo() == null || fileRecordVO.getDeviceNo().trim().isEmpty()) {
            missingFields.add("台架编号");
        }
        if (fileRecordVO.getCompany() == null || fileRecordVO.getCompany().trim().isEmpty()) {
            missingFields.add("单位");
        }
        if (fileRecordVO.getDataTypeFirst() == null) {
            missingFields.add("数据第一分类");
        }
        if (fileRecordVO.getDataTypeSecond() == null) {
            missingFields.add("数据第二分类");
        }
        if (fileRecordVO.getProductPhase() == null) {
            missingFields.add("产品阶段");
        }
        if (fileRecordVO.getDataSource() == null || fileRecordVO.getDataSource().trim().isEmpty()) {
            missingFields.add("数据来源");
        }
        if (fileRecordVO.getStartTime() == null) {
            missingFields.add("运行起始时间");
        }
        if (fileRecordVO.getEngineNo() == null || fileRecordVO.getEngineNo().trim().isEmpty()) {
            missingFields.add("发动机编号");
        }

        if (!missingFields.isEmpty()) {
            result.put("success", false);
            result.put("message", "请填写以下必填字段后再导入：" + String.join("、", missingFields));
        } else {
            result.put("success", true);
        }

        return result;
    }

    /**
     * 根据导入结果创建单个import_task记录
     */
    private Map<String, Object> createSingleImportTaskWithResult(FileRecordVO fileRecordVO, Map<String, Object> importResult) {
        try {
                log.info("开始根据导入结果创建单个import_task记录，文件名: {}", fileRecordVO.getFileName());
                
                // 获取导入结果详情
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> importResults = (List<Map<String, Object>>) importResult.get("importResults");
                
                if (importResults == null || importResults.isEmpty()) {
                    log.warn("导入结果为空，无法创建import_task记录");
                    return createErrorResult("导入结果为空，无法创建import_task记录");
                }
                
                // 获取第一个导入结果（单个文件导入只有一个结果）
                Map<String, Object> result = importResults.get(0);
                
                // 查询已存在的ImportTask
                ImportTask existingTask = importTaskService.findSuccessImportByFileName(fileRecordVO.getFileName());
                
                ImportTask importTask = convertFileRecordVOToImportTask(fileRecordVO);
                
                if (existingTask != null) {
                    // 如果已存在，retrytime +1
                    importTask.setRetryTime(existingTask.getRetryTime() + 1);
                } else {
                    // 如果不存在，retrytime为1
                    importTask.setRetryTime(1);
                }

                // 根据导入结果设置import_status
                boolean success = (Boolean) result.getOrDefault("success", false);
                importTask.setImportStatus(success ? 1 : 2); // 1-导入成功；2-导入失败
                
                // 如果导入失败，记录错误信息，并将错误信息放入remark字段
                if (!success) {
                    String errorMessage = (String) result.getOrDefault("message", "导入失败");
                    log.warn("文件 {} 导入失败: {}", fileRecordVO.getFileName(), errorMessage);
                    // 将错误信息放入remark字段
                    importTask.setRemark(errorMessage);
                }
                
                // 调用Service层进行插入
                boolean insertResult = importTaskService.createImportTask(importTask);
                
                if (insertResult) {
                    log.info("根据导入结果创建单个import_task记录成功，文件名: {}", fileRecordVO.getFileName());
                    return createSuccessResult("成功创建import_task记录", null);
                } else {
                    log.error("根据导入结果创建单个import_task记录失败，文件名: {}", fileRecordVO.getFileName());
                    return createErrorResult("根据导入结果创建单个import_task记录失败");
                }
        } catch (Exception e) {
            log.error("根据导入结果创建单个import_task记录时发生异常", e);
            return createErrorResult("根据导入结果创建单个import_task记录时发生异常: " + e.getMessage());
        }
    }

    /**
     * 将FileRecordVO转换为ImportTask
     */
    private ImportTask convertFileRecordVOToImportTask(FileRecordVO fileRecordVO) {
        ImportTask importTask = new ImportTask();
        
        // 复制基本信息
        importTask.setFileName(fileRecordVO.getFileName());
        importTask.setProjectNo(fileRecordVO.getProjectNo());
        importTask.setPlace(fileRecordVO.getPlace());
        importTask.setCompany(fileRecordVO.getCompany());
        importTask.setProductPhase(fileRecordVO.getProductPhase());
        importTask.setDataTypeFirst(fileRecordVO.getDataTypeFirst());
        importTask.setDataTypeSecond(fileRecordVO.getDataTypeSecond());
        importTask.setDataSource(fileRecordVO.getDataSource());
        importTask.setStartTime(fileRecordVO.getStartTime());
        importTask.setEngineId(fileRecordVO.getEngineId());
        importTask.setEngineNo(fileRecordVO.getEngineNo());
        importTask.setChannelNo(fileRecordVO.getChannelNo());
        importTask.setDeviceNo(fileRecordVO.getDeviceNo());
        importTask.setEnginePlace(fileRecordVO.getEnginePlace());
        importTask.setEcuId(fileRecordVO.getEcuId());
        importTask.setEcuNo(fileRecordVO.getEcuNo());
        importTask.setEcuSysId(fileRecordVO.getEcuSysId());
        importTask.setEcuSysNo(fileRecordVO.getEcuSysNo());
        importTask.setSubject(fileRecordVO.getSubject());
        importTask.setRemark(fileRecordVO.getRemark());
        importTask.setCheckCode(fileRecordVO.getCheckCode());
        importTask.setSyncDataSource(fileRecordVO.getSyncDataSource());
        
        // 设置默认值
        importTask.setSyncStatus(0); // 默认未同步
        importTask.setCreateTime(LocalDateTime.now()); // 设置创建时间
        
        return importTask;
    }


}
